package com.lee.common.util;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取用户真实ip
 *
 * @author lee HN
 * @date 2021/5/8 14:54
 */
public final class IpAddrUtil {

    public static String obtainIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        // 多次反向代理后会有多个ip值，第一个ip才是真实ip
        if (!ipInvalid(ip)) {
            int index = ip.indexOf(",");
            ip = index == -1 ? null : ip.substring(0, index);
        }

        if (ipInvalid(ip)) ip = request.getHeader("Proxy-Client-IP");

        if (ipInvalid(ip)) ip = request.getHeader("WL-Proxy-Client-IP");

        if (ipInvalid(ip)) ip = request.getHeader("HTTP_CLIENT_IP");

        if (ipInvalid(ip)) ip = request.getHeader("HTTP_X_FORWARDED_FOR");

        if (ipInvalid(ip)) ip = request.getHeader("X-Real-IP");

        if (ipInvalid(ip)) ip = request.getRemoteAddr();

        return ip;
    }

    private static boolean ipInvalid(String ip) {
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }

}
